<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\track\XhtrackTaskstate;
use Admin\Models\user\XhsysUser;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Tool;
use Modules\Power;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Helpers\User;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\track\XhtrackTask;
use Admin\Models\track\XhtrackTaskAssign;
use Admin\Models\pm\XhpmProduct;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\sys\XhsysClassification;
use Helpers\UserPower;
use Modules\School;
use Phalcon\Db\Column;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Services\App;

class TrackController extends ControllerBase
{

    public $taskType = [1 => '需求', 2 => 'BUG', 3 => '资源'];
    private $publicState = [0 => '新建', 1 => '已完成'];
    private $priority = [1 => '低', 2 => '中', 3 => '高'];
    private $taskState = [
        1 => [
            30 => '设计审核',      //
            33 => '暂停',
            34 => '退回',
            40 => '开发中',        //
            50 => '测试中',        //
            99 => '已发布'
        ],
        2 => [
            32 => '待处理',
            33 => '暂停',
            35 => '已解决(非bug)',        //new
            36 => '表象解决',      //new
            37 => '未定位',        //new
            38 => '已定位',        //new
            40 => '开发中',        //
            50 => '测试中',        //
            99 => '已发布'
        ],
        3 => [
            33 => '暂停',
            34 => '退回',
            40 => '录入中',        //
            50 => '校对中',        //
            99 => '已发布'
        ]
    ];
    private $oldTaskState = [
        1 => [
            2 => '不开发',
            3 => '后期开发',
            6 => '开发进行中',
            7 => '3.0开发',
            9 => '已解决',
            10 => '学校待确认',
            11 => '需求不明确',
            12 => '需确认'
        ],
        2 => [
            2 => '开发进行中',
            4 => '已解决',
            5 => '学校待确认',
            6 => '需求不明确'
        ],
        3 => [
            2 => '资料录入',
            3 => '校对完成',
            4 => '学校待确认',
            5 => '需求不明确'
        ]
    ];
    private $confirmState = [
        1 => [
            0 => '未确认',
            1 => '确认完成',
        ],
        2 => [
            0 => '未确认',
            1 => '确认完成',
        ],
        3 => [
            0 => '未确认',
            11 => '继续录入',
            22 => '有问题待解决',
            33 => '不需要录入',
            44 => '录入完成'
        ]
    ];
    private static $productTypes = [
        1 => '学生',
        2 => '教师',
        3 => '家长',
        4 => '通用',
        5 => '服务端',
    ];

    private static $proLevel = [
        1 => '紧要',
        2 => '紧急',
        3 => '重要',
        4 => '一般',
        5 => '偶发',
    ];

    private $techSupportStatus = [
        0 => '新建',
        7 => '接收',
        8 => '处理',
        9 => '解决',
        1 => '完成',
    ];

    /**
     * 根据任务类型，状态ID获取状态名称
     *
     * @param $taskType
     * @param $stateId
     * @return mixed
     *
     * create by ck 20170320
     */
    public function getStateName($taskType, $stateId)
    {
        if (in_array($stateId, [0, 1])) {
            return $this->publicState[$stateId];
        }
        if (isset($this->oldTaskState[$taskType][$stateId])) {
            return $this->oldTaskState[$taskType][$stateId];
        }
        if (isset($this->techSupportStatus[$stateId])) {
            return $this->techSupportStatus[$stateId];
        }
        return $this->taskState[$taskType][$stateId];
    }

    /**
     * 问题跟踪
     *
     * @param $taskType
     * @param $iState
     * @param $iSupportState
     *
     * @return array
     *
     * create by zqk 20181109
     */
    public function getProStateName($taskType, $iState, $iSupportState)
    {
        $state = [];
        $state['iState'] = isset($this->taskState[$taskType][$iState]) ? $this->taskState[$taskType][$iState] : '未指派';
        if (isset($this->techSupportStatus[$iSupportState])) {
            $state['iSupportState'] = $this->techSupportStatus[$iSupportState];
        } elseif ($iSupportState == 1) {
            $state['iSupportState'] = '已完成';
        }
        return $state;
    }

    /**
     * 根据任务类型，确认状态获取名称
     *
     * @param $taskType
     * @param $stateId
     * @return mixed
     *
     * create by ck 20170510
     */
    private function getConfirmStateName($taskType, $stateId = null)
    {
        return isset($this->confirmState[$taskType][$stateId]) ? $this->confirmState[$taskType][$stateId] : $this->confirmState[$taskType][0];
    }

    /**
     * 获取应用及包名数组
     *
     * @param null $taskType
     * @param bool|false $onlyName
     * @return array
     *
     * create by ck 20170316
     * modify by ck 20170331    如为资源任务，则不返回
     * modify by ck 20170410    可重复使用，节约资源
     * modify by ck 20180507    更改为新应用列表
     */
    private function getAppInfoArr($taskType = null, $onlyName = false)
    {
        static $apps;
        if ($taskType == 3) {
            return [];
        }
        if (!$apps) {
            $apps = App::getAppNames(true);
        }
        return $onlyName ? array_combine($apps, $apps) : $apps;
    }

    /**
     * 增加日志
     *
     * @param XhtrackTask $obj
     * @param $type
     * @param $content
     * @param $explain
     * @param string $level
     *
     * create by ck 20170330
     */
    private function dealChangeLog(XhtrackTask $obj, $type, $content, $explain, $level = '')
    {
        $obj->mStateLog = array_values(array_merge([[
            'operate' => $type,
            'msg' => $content,
            'explain' => $explain,
            'level' => $level,
            'userId' => Main::getLoginUserInfo('userId'),
            'userName' => Main::getLoginUserInfo('userName'),
            'changeTime' => date('Y-m-d H:i:s')
        ]], (array)$obj->mStateLog));
    }

    /**
     * 检查操作权限
     *
     * @param $taskType
     * @param string $power
     * @return bool
     *
     * create by ck 20170330
     */
    private function checkOperatePower($taskType = null, $power = '')
    {
        $power and $power = '_' . $power;
        switch ($taskType) {
            case 1:
                return UserPower::checkUserPower('Track_Demand' . $power);
            case 2:
                return UserPower::checkUserPower('Track_BUG' . $power);
            case 3:
                return UserPower::checkUserPower('Track_Res' . $power);
            default:
                return UserPower::checkUserPower('Track' . $power);
        }
    }

    /**
     * 跟踪问题列表页面
     *
     * create by ck 20170314
     * modify by ck 20170510    添加确认状态
     * modify by ck 20171019    技术部可修改计划完成时间/解决版本
     * modify by dale 20180224  添加教师角色需求bug资源处理
     */
    public function trackTaskListAction()
    {
        $userId = $this->request->getQuery('userId');
        $this->view->pick('track/trackTaskList');
        $taskType = $this->request->getQuery('iTaskType', 'int');
        if ($taskType == 2) {
            Assets::UEditor();
        } else {
            Assets::UMEditor();
        }
        Assets::select2();
        Assets::easyUI('js/track/trackTaskList.js');
        if (!$userId) {
            Main::showNavPosition($this->taskType[$taskType] . '跟踪');
        }
        $this->checkOperatePower($taskType) or die(Main::showMessageModal('抱歉，您没有查看此页面的权限！'));
        Template::exists('XHTrack_Task', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listButtonArr = $listSearchArr = $formButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_State', 'style' => 'width:100px;', 'data' => ['' => '--状态--'] + $this->publicState + $this->taskState[$taskType]];
        isset($this->confirmState[$taskType]) and $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_ConfirmState', 'style' => 'width:100px;', 'data' => ['' => '--确认状态--'] + $this->confirmState[$taskType]];
        if ($taskType == 2) {
            $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_CreatorName', 'style' => 'width:150px;', 'label' => ' 创建人：', 'data' => ['0' => '--选择--'] + $this->getAllStaff()];
            $listSearchArr[] = ['type' => 'select', 'id' => 'iReportUserId', 'style' => 'width:150px;', 'label' => ' 上报人：'];
            $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'List_Search_StartDate', 'label' => ' 提交日期：'];
        } else {
            $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'List_Search_StartDate', 'label' => ' 计划日期：'];
        }
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'List_Search_EndDate', 'label' => ' ~ ', 'style' => 'width:110px;'];
        $schoolArr = School::getPower(true);
        $schoolArr === true and $schoolArr = XhschoolInfo::getSchoolSupportArray();
        if ($taskType == 3) {
            if (!$userId) {
                $schoolArr and $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_SchoolId', 'label' => ' 学校：', 'data' => [0 => '--选择--'] + $schoolArr];
            }
        } else {
//            $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_AppName', 'label' => ' 应用：', 'data' => array_merge(['' => '--选择--'], $this->getAppInfoArr($taskType, true))];
            $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_AppName', 'style' => 'width:150px;', 'label' => ' 应用：', 'data' => ['0' => '--选择--'] + $this->getProducts()];
        }
        $listSearchArr[] = ['type' => 'text', 'style' => 'width:50px;', 'class' => 'easyui-textbox', 'id' => 'list_search', 'label' => ' 任务：'];
        if ($taskType == 2) {
            $schoolArr and $listSearchArr[] = ['type' => 'select', 'style' => 'width:140px;', 'id' => 'List_Search_SchoolId', 'label' => ' 学校：', 'data' => [0 => '--选择--'] + $schoolArr];
            $listSearchArr[] = ['type' => 'select', 'id' => 'proType', 'style' => 'width:150px;', 'label' => ' 问题分类：'];
            $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        }
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:0px'];
        if ($this->checkOperatePower($taskType, 'Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus'];
//            $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '增加', 'class' => 'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if ($this->checkOperatePower($taskType, 'Edit')) {
//            $formButtonArr[] = ['id' => 'bt_form_edit', 'text' => '修改', 'class' => 'disabled'];
            $this->view->setVar('AddEdit', true);
        }
        if ($taskType == 2) {
            if ($this->checkOperatePower($taskType, 'TechState')) {
                $listButtonArr[] = ['id' => 'bt_list_TechState', 'class' => 'menubutton', 'text' => '开发状态', 'plain' => 'true', 'icon' => 'fa-exchange'];
                $this->view->setVar('AddEdit', true);
            }
            if ($this->checkOperatePower($taskType, 'SuppState')) {
                $listButtonArr[] = ['id' => 'bt_list_SuppState', 'class' => 'menubutton', 'text' => '任务状态', 'plain' => 'true', 'icon' => 'fa-exchange'];
                $this->view->setVar('AddEdit', true);
            }
            $listButtonArr[] = ['id' => 'bt_list_Log', 'text' => '状态变更日志', 'plain' => 'true', 'icon' => 'fa-eye'];

        } else {
                $listButtonArr[] = ['id' => 'bt_list_SetState', 'class' => 'menubutton', 'text' => '更改状态', 'plain' => 'true', 'icon' => 'fa-exchange'];
        }

        if ($this->checkOperatePower(0, 'Confirm')) {
            $listButtonArr[] = ['id' => 'bt_list_SchoolConfirm', 'text' => '学校确认', 'plain' => 'true', 'icon' => 'fa-institution'];
        }
        if ($this->checkOperatePower($taskType, 'Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if ($taskType == 2 && (UserPower::checkUserPower('Track_BUG_Assign') || UserPower::checkUserPower('Track_BUG_Move'))) {
            $listButtonArr[] = ['id' => 'bt_list_assign', 'class' => 'menubutton', 'text' => '指派', 'plain' => 'true', 'icon' => 'fa-hand-o-right'];
        }
//        $formButtonArr[] = ['id' => 'bt_form_back', 'text' => '返回'];
//        $formButtonArr[] = ['id' => 'bt_form_reset', 'text' => '重置'];
        if ($taskType == 3) {
            $formName = 'XHTrack_Task_Res';
        } elseif ($taskType == 2) {
            $formName = 'XHTrack_Task_Question';
        } else {
            $formName = 'XHTrack_Task';
        }
        $this->view->setVars([
            'List' => Template::createList('List', $formName, [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
//            'Form' => Template::createForm($formName),
//            'FormButton' => Template::createButtonToolBar($formButtonArr),
            'useful' => json_encode([
                'schoolArr' => $schoolArr,
                'stateArr' => $this->taskState[$taskType],
                'suppState' => $this->techSupportStatus,
//                'appArr'    => $this->getAppInfoArr($taskType),
                'appArr' => $this->getProducts(),
                'isTech' => in_array('TECH', Main::getLoginUserInfo('depTag')) || Main::getLoginUserInfo('logonName') == 'admin',
            ]),
            'movePower' => UserPower::checkUserPower('Track_BUG_Move'),
            'assignPower' => UserPower::checkUserPower('Track_BUG_Assign'),
            'userType' => Main::getLoginUserInfo('userType'),
            'proLevel' => self::$proLevel,
        ]);
    }

    /**
     * 获取问题反馈列表
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by zqk 20181019
     */
    public function getProTrackTaskDataAction()
    {
        $taskType = $this->request->getPost('taskType', 'int');
        $startDate = $this->request->getPost('startDate', 'string');
        $endDate = $this->request->getPost('endDate', 'string');
        $state = $this->request->getPost('state', 'int');
        $confirmState = $this->request->getPost('confirmState', 'int');
        $vague = $this->request->getPost('vague', 'string');
        $schoolName = trim($this->request->getPost('schoolName', 'string'));
        $schoolId = $this->request->getPost('schoolId', 'int');
        $iReportUserId = $this->request->getPost('iReportUserId', 'int');
        $iProductId = $this->request->getPost('iProductId'); //数组
        $proName = $this->request->getPost('proName'); //数组
        $creatorId = $this->request->getPost('creatorId'); //数组
        $userId = $this->request->getPost('userId', 'int');
        $loginUserId = Main::getLoginUserInfo('userId');
        $params = [
            "taskType" => $taskType,
            "startDate" => $startDate,
            "endDate" => $endDate,
            "state" => $state,
            "confirmState" => $confirmState,
            "vague" => $vague,
            "schoolName" => $schoolName,
            "schoolId" => $schoolId,
            "iReportUserId" => $iReportUserId,
            "userId" => $userId,
            "loginUserId" => $loginUserId,
            "proName" => $proName,
            "iProductId" => $iProductId,
            "creatorId" => $creatorId,
        ];
        $data = $this->getProTrackTaskData($params);
        return $this->response->setJsonContent($data);
    }

    /**
     * 获取问题反馈数据
     *
     * @param array $params
     * @param bool $ifExport
     *
     * @return array|string
     * @throws \Exception
     *
     * create by zqk 20181019
     */
    public function getProTrackTaskData($params = [], $ifExport = false)
    {
        try {
            $taskType = $params['taskType'];
            $startDate = $params['startDate'];
            $endDate = $params['endDate'];
            $state = $params['state'];
            $confirmState = $params['confirmState'];
            $vague = $params['vague'];
            $schoolName = $params['schoolName'];
            $schoolId = $params['schoolId'];
            $iReportUserId = $params['iReportUserId'];
            $iProductId = $params['iProductId'];
            $creatorId = $params['creatorId'];
            $proName = $params['proName'];
            $userId = $params['userId'];
            $loginUserId = $params['loginUserId'];
            $conditions = 't.bDelete = 0';
            $columns = 't.iTTId,t.sTaskName,t.sTaskContent,t.iTaskType,t.iPriority,t.tOfferTime,t.tPlanFinishTime,t.tRealFinishTime,t.iState,t.mStateLog,t.iLastModifyUserId,t.tLastModifyDate,t.sOfferIds,t.sOfferUserName,t.iProductId,t.sSolveVersion,t.iProblemStyle,t.iSupportState,
            t.iReportUserId,t.iProLevel,t.iConfirmState,t.sSchoolId,t.mRemarks,t.iCreateUserId,c.sName,t.sAppVersion,t.iInfluenceNum,t.dHandlingTime,t.sReason,t.sSolveWay,t.sVersion';
            //过滤任务类型
            if ($taskType) {
                $conditions .= " AND t.iTaskType = $taskType";
            }
            //过滤开始日期
            if ($startDate) {
                $conditions .= " AND t.tOfferTime >= '$startDate'";
            }
            //过滤结束日期
            if ($endDate) {
                $conditions .= " AND t.tOfferTime <= '$endDate'";
            }
            //过滤应用包名
            if ($iProductId) {
                $ke = array_search(0, $iProductId);
                if ($ke !== false) {
                    unset($iProductId[$ke]);
                }
                if (!empty($iProductId)) {
                    $iProductId = implode(',', $iProductId);
                    $conditions .= " AND t.iProductId in ($iProductId)";
                }
            }
            //过滤问题分类
            if ($proName) {
                $ke = array_search(0, $proName);
                if ($ke !== false) {
                    unset($proName[$ke]);
                }
                if (!empty($proName)) {
                    $proName = implode(',', $proName);
                    $conditions .= " AND t.iProblemStyle in ($proName)";
                }
            }
            //过滤创建人
            if ($creatorId) {
                $ke = array_search(0, $creatorId);
                if ($ke !== false) {
                    unset($creatorId[$ke]);
                }
                if (!empty($creatorId)) {
                    $creatorId = implode(',', $creatorId);
                    $conditions .= " AND t.iCreateUserId in ($creatorId)";
                }

            }
            //过滤上报人
            if ($iReportUserId) {
                $conditions .= " AND t.iReportUserId = $iReportUserId";
            }
            //过滤学校ID
            if ($schoolId) {
                $conditions .= " AND t.sSchoolId like '%,{$schoolId},%'";
            }
            //过滤学校名字
            if ($schoolName) {
                if (strpos($schoolName, ',') !== false) {
                    $schoolName = explode(',', $schoolName);
                } elseif (strpos($schoolName, ' ') !== false) {
                    $schoolName = explode(' ', $schoolName);
                } else {
                    $schoolName = [$schoolName];
                }
                $schoolId = [];
                $schoolArr = XhschoolInfo::getSchoolSupportArray();
                foreach ($schoolName as $schName) {
                    foreach ($schoolArr as $key => $value) {
                        if (strstr($value, $schName)) {
                            $schoolId[] = $key;
                        }
                    }
                }
                if (!$schoolId) {
                    $conditions .= 'AND t.sSchoolId IN (0)';
                } else {
                    $schoolConditions = [];
                    foreach ($schoolId as $schId) {
                        $schoolConditions[] = "t.sSchoolId like '%,{$schId},%'";
                    }
                    $conditions .= ' AND (' . implode(' OR ', $schoolConditions) . ')';
                }
            }
            if ($vague) {
                $conditions .= " AND (t.sTaskName like '%{$vague}%')";
            }
            if ($userId) {
                $conditions .= " AND (t.sOfferIds like '%,{$userId},%')";
            }
            if ($state != '') {
                $conditions .= " AND t.iState = $state";
            }
            if ($confirmState) {
                $conditions .= " AND t.iConfirmState = $confirmState";
            }
            $conditions1 = $conditions;
            //获取指派的任务Ids
            $assignTaskIds = XhtrackTaskAssign::find([
                'columns' => 'iTTId',
                'conditions' => 'bDelete = 0 AND iUserId = ' . $loginUserId,
            ])->toArray();
            $assignTaskIds = array_column($assignTaskIds, 'iTTId');
            //过滤学校权限  //以及或者是创建人  //过滤应用
            $authorizationSchoolIdArr = School::getPower();
            $productIds = Power::getextrapower('product', 'productList');  //获取扩展部门权限
            if ($productIds === true) {
                $productIds = XhpmProduct::find([
                    'columns' => 'iId,sName,iType',
                    'conditions' => 'bDelete = 0',
                ])->toArray();
                $productIds = array_column($productIds, 'iId');
            }
            $productTaskIds = $this->modelsManager->createBuilder()
                ->columns("t.iTTId")
                ->addFrom('Admin\Models\track\XhtrackTask', 't')
                ->where($conditions)
                ->inWhere('t.iProductId', $productIds)
                ->getQuery()
                ->execute()
                ->toArray();
            $iTTIds = [];
            if (!$authorizationSchoolIdArr && empty($assignTaskIds)) {
                return false;
            } elseif (empty($productIds) && empty($assignTaskIds)) {
                return false;
            } elseif ($authorizationSchoolIdArr !== true && !empty($authorizationSchoolIdArr)) {
                $schoolConditions = [];
                foreach ($authorizationSchoolIdArr as $schId) {
                    $schoolConditions[] = "t.sSchoolId like '%,{$schId},%'";
                }
                $conditions .= ' AND (' . implode(' OR ', $schoolConditions) . " OR t.iCreateUserId = $loginUserId " . ')';
                $schoolTaskIds = $this->modelsManager->createBuilder()
                    ->columns("iTTId")
                    ->addFrom('Admin\Models\track\XhtrackTask', 't')
                    ->where($conditions)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $iTTIds = array_unique(array_intersect(array_column($productTaskIds, 'iTTId'), array_column($schoolTaskIds, 'iTTId')));
            } elseif ($authorizationSchoolIdArr == true) {
                $conditions .= " and ( t.iCreateUserId = $loginUserId )";
                $createTaskIds = $this->modelsManager->createBuilder()
                    ->columns("t.iTTId")
                    ->addFrom('Admin\Models\track\XhtrackTask', 't')
                    ->where($conditions)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $iTTIds = array_merge($productTaskIds, $createTaskIds);
                $iTTIds = array_unique(array_column($iTTIds, 'iTTId'));
            }
            $iTTIds = array_unique(array_merge($iTTIds, $assignTaskIds));
            if ($ifExport) {
                $result = $this->modelsManager->createBuilder()
                    ->columns($columns)
                    ->addFrom('Admin\Models\track\XhtrackTask', 't')
                    ->leftJoin('Admin\Models\sys\XhsysClassification', 't.iProblemStyle = c.id', 'c')
                    ->where($conditions1)
                    ->inWhere('t.iTTId', $iTTIds)
                    ->orderBy('t.iTTId desc')
                    ->getQuery()
                    ->execute()
                    ->toArray();
            } else {
                $builder = $this->modelsManager->createBuilder()
                    ->columns($columns)
                    ->addFrom('Admin\Models\track\XhtrackTask', 't')
                    ->leftJoin('Admin\Models\sys\XhsysClassification', 't.iProblemStyle = c.id', 'c')
                    ->where($conditions1)
                    ->inWhere('t.iTTId', $iTTIds)
                    ->orderBy('t.iTTId desc');
                $taskDatas = Main::runBuilderPages($builder, true);
                $result = $taskDatas['rows'];
            }
            $apps = XhpmProduct::find([
                'columns' => 'iId,sName,iType',
                'conditions' => 'bDelete = 0'
            ])->toArray();
            $appNames = array_column($apps, 'sName', 'iId');
            $appTypes = array_column($apps, 'iType', 'iId');
            $level = self::$proLevel;
            foreach ($result as &$row) {
                $stateArr = $this->getProStateName($taskType, $row['iState'], $row['iSupportState']);
                $row['iState'] = $stateArr['iState'];
                $row['iSupportState'] = $stateArr['iSupportState'];
                $row['iProLevel'] = isset($level[$row['iProLevel']]) ? $level[$row['iProLevel']] : '';
                isset($row['iPriority']) and $row['iPriority'] = $this->priority[$row['iPriority']];
                isset($row['iConfirmState']) and $row['iConfirmState'] = $this->getConfirmStateName($row['iTaskType'], $row['iConfirmState']);
                //处理日志中最后修改状态人姓名
                if (isset($row['mStateLog'])) {
                    $row['mStateLog'] = json_decode(base64_decode($row['mStateLog']), true);
                    foreach ($row['mStateLog'] as $log) {
                        if ($log['operate'] == '更改状态') {
                            $row['iState'] .= "({$log['userName']})";
                            break;
                        }
                    }
                    unset($row['mStateLog']);
                }
                //处理应用名
                $productId = isset($row['iProductId']) ? $row['iProductId'] : 0;
                if (!empty($appNames[$productId])) {
                    $productType = $appTypes[$productId];
                    $row['sAppName'] = $appNames[$productId] . '(' . self::$productTypes[$productType] . ')';
                }
                if ($ifExport) {
                    $row['sTaskContent'] = strip_tags($row['sTaskContent']);
                }
            }
            unset($row);
            //处理学校名
            Main::runSchoolNameByIdStr($result, ['sSchoolId' => 'sSchoolName'], true);
            //组合提问人姓名
            Main::runUserName($result, ['sOfferIds' => 'sOfferUserName', 'iCreateUserId' => 'iCreateUserName', 'iReportUserId' => 'iReportUserName'], true);
            if (!empty($taskDatas)) {
                $taskDatas['rows'] = $result;
                return $taskDatas;
            } else {
                return $result;
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取跟踪问题列表
     *
     * @param bool $home
     * @param null $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20170314
     * modify by ck 20170329    区分资料及其他
     * modify by ck 20170331    学校支持批量筛选，可筛选名称/ID
     * modify by ck 20170417    添加用户学校权限，可根据学校ID筛选
     * modify by ck 20170622    添加最后修改状态人姓名字段
     * modify by ck 20171018    支持窗体展示获取信息
     * modify by dale 20180224  添加提问者过滤
     * modify by dale 20190130  由于iProdId为数组引发的prodId多选时触发问题
     */
    public function getTrackTaskDataAction($home = false, $type = null)
    {
        try {
            $taskType = $this->request->getPost('taskType', 'int');
            $startDate = $this->request->getPost('startDate', 'string');
            $endDate = $this->request->getPost('endDate', 'string');
            $state = $this->request->getPost('state', 'int');
            $confirmState = $this->request->getPost('confirmState', 'int');
            $vague = $this->request->getPost('vague', 'string');
            $schoolName = trim($this->request->getPost('schoolName', 'string'));
            $schoolId = $this->request->getPost('schoolId', 'int');
            $iProductId = $this->request->getPost('iProductId', 'int');
            $userId = $this->request->getPost('userId', 'int');
            $parameters = [
                'conditions' => 'bDelete = 0',
                'order' => 'iTTId desc'
            ];
            if (!$home) {
                $parameters['columns'] = 'iTTId,sTaskName,iTaskType,iPriority,tOfferTime,tPlanFinishTime,tRealFinishTime,iState,mStateLog,iLastModifyUserId,tLastModifyDate,tCreateDate,iCreateUserId,sOfferIds,sOfferUserName';
                if ($taskType == 3) {
                    $parameters['columns'] .= ',iConfirmState,sSchoolId,mRemarks';
                } else {
                    $parameters['columns'] .= ',iProductId,sSolveVersion';
                }
            } else {
                $parameters['columns'] = 'iTTId,sTaskName,iState,tCreateDate';
                $taskType = $type;
                $parameters['limit'] = 5;
            }

            //过滤部门创建人权限
            if (!$this->checkOperatePower($taskType, 'All')) {
                $createUserIds = Hrm::getDepUserIdByUser();
                $parameters['conditions'] .= ' AND iCreateUserId IN ({userIds:array})';
                $parameters['bind']['userIds'] = $createUserIds;
            }

            //过滤学校权限
            $authorizationSchoolIdArr = School::getPower();
            if (!$authorizationSchoolIdArr) {
                if ($home) {
                    throw new \Exception('无学校权限');
                }
                return $this->sendDataGridError('无学校权限');
            } elseif ($authorizationSchoolIdArr !== true) {
                $schoolConditions = [];
                foreach ($authorizationSchoolIdArr as $schId) {
                    $schoolConditions[] = "sSchoolId like '%,{$schId},%'";
                }
                $parameters['conditions'] .= ' AND (' . implode(' OR ', $schoolConditions) . ')';
            }

            //过滤任务类型
            if ($taskType) {
                $parameters['conditions'] .= ' AND iTaskType = :iTaskType:';
                $parameters['bind']['iTaskType'] = $taskType;
                $parameters['bindType']['iTaskType'] = Column::BIND_PARAM_INT;
            }

            //过滤开始日期
            if ($startDate) {
                $parameters['conditions'] .= ' AND tPlanFinishTime >= :startDate:';
                $parameters['bind']['startDate'] = $startDate;
                $parameters['bindType']['startDate'] = Column::BIND_PARAM_STR;
            }
            //过滤结束日期
            if ($endDate) {
                $parameters['conditions'] .= ' AND tPlanFinishTime <= :endDate:';
                $parameters['bind']['endDate'] = $endDate;
                $parameters['bindType']['endDate'] = Column::BIND_PARAM_STR;
            }

            //过滤应用名称
//            if ($appName) {
//                $parameters['conditions'] .= ' AND sAppName like :appName:';
//                $parameters['bind']['appName'] = '%' . $appName . '%';
//                $parameters['bindType']['appName'] = Column::BIND_PARAM_STR;
//            }
            //过滤应用包名 bug
            if ($iProductId) {
                $prodArr = array_filter($iProductId);
                if ($prodArr) {
                    $parameters['conditions'] .= ' AND iProductId in ({prodIds:array}) ';
                    $parameters['bind']['prodIds'] =  $prodArr;
                    $parameters['bindType']['prodIds'] = Column::BIND_SKIP;
                }
            }
            //过滤学校ID
            if ($schoolId) {
                $parameters['conditions'] .= ' AND sSchoolId like :schoolId:';
                $parameters['bind']['schoolId'] = "%,{$schoolId},%";
                $parameters['bindType']['schoolId'] = Column::BIND_PARAM_STR;
            }

            //过滤学校名字
            if ($schoolName) {
                if (strpos($schoolName, ',') !== false) {
                    $schoolName = explode(',', $schoolName);
                } elseif (strpos($schoolName, ' ') !== false) {
                    $schoolName = explode(' ', $schoolName);
                } else {
                    $schoolName = [$schoolName];
                }
                $schoolId = [];
                $schoolArr = XhschoolInfo::getSchoolSupportArray();
                foreach ($schoolName as $schName) {
                    foreach ($schoolArr as $key => $value) {
                        if (strstr($value, $schName)) {
                            $schoolId[] = $key;
                        }
                    }
                }
                if (!$schoolId) {
                    $parameters['conditions'] .= 'AND sSchoolId IN (0)';
                } else {
                    $schoolConditions = [];
                    foreach ($schoolId as $schId) {
                        $schoolConditions[] = "sSchoolId like '%,{$schId},%'";
                    }
                    $parameters['conditions'] .= ' AND (' . implode(' OR ', $schoolConditions) . ')';
                }
            }

            if ($vague) {
                $parameters['conditions'] .= ' AND (sTaskName like :sTaskName: OR iTTId = :iTTId:)';
                $parameters['bind']['sTaskName'] = '%' . $vague . '%';
                $parameters['bind']['iTTId'] = $vague;
                $parameters['bindType']['sTaskName'] = Column::BIND_PARAM_STR;
                $parameters['bindType']['iTTId'] = Column::BIND_PARAM_STR;
            }
            if ($userId) {
                $parameters['conditions'] .= ' AND sOfferIds like :offerId: ';
                $parameters['bind']['offerId'] = '%,' . $userId . ',%';
                $parameters['bindType']['offerId'] = Column::BIND_PARAM_STR;
            }

            if ($state != '') {
                $parameters['conditions'] .= ' AND iState = :iState:';
                $parameters['bind']['iState'] = $state;
                $parameters['bindType']['iState'] = Column::BIND_PARAM_INT;
            }
            if ($confirmState) {
                $parameters['conditions'] .= ' AND iConfirmState = :iConfirmState:';
                $parameters['bind']['iConfirmState'] = $confirmState;
                $parameters['bindType']['iConfirmState'] = Column::BIND_PARAM_INT;
            }
//            var_dump($parameters);die;
            $result = Main::runModelPage('\\Admin\\Models\\track\\XhtrackTask', $parameters);

//            $appNames = $this->getAppInfoArr($taskType, false);
            $apps = XhpmProduct::find([
                'columns' => 'iId,sName,iType',
                'conditions' => 'bDelete = 0'
            ])->toArray();
            $appNames = array_column($apps, 'sName', 'iId');
            $appTypes = array_column($apps, 'iType', 'iId');
            foreach ($result['rows'] as &$row) {
                $row['iState'] = $this->getStateName($taskType, $row['iState']);
                isset($row['iPriority']) and $row['iPriority'] = $this->priority[$row['iPriority']];
                isset($row['iConfirmState']) and $row['iConfirmState'] = $this->getConfirmStateName($row['iTaskType'], $row['iConfirmState']);
                //处理日志中最后修改状态人姓名
                if (isset($row['mStateLog'])) {
                    $row['mStateLog'] = json_decode(base64_decode($row['mStateLog']), true);
                    foreach ($row['mStateLog'] as $log) {
                        if ($log['operate'] == '更改状态') {
                            $row['iState'] .= "({$log['userName']})";
                            break;
                        }
                    }
                    unset($row['mStateLog']);
                }
                //处理应用名
                if (!$home && $type != 3) {
                    $productId = isset($row['iProductId']) ? $row['iProductId'] : 0;
                    if (!empty($appNames[$productId])) {
                        $productType = $appTypes[$productId];
                        $row['sAppName'] = $appNames[$productId] . '(' . self::$productTypes[$productType] . ')';
                    }
                }
            }
            unset($row);

            if ($taskType == 3 && !$home) {
                Main::runSchoolNameByIdStr($result['rows'], ['sSchoolId' => 'sSchoolId'], true);
            }

            //组合提问人姓名
            if (!$home) {
                Main::runUserName($result['rows'], ['sOfferIds' => 'sOfferUserName'], true);
            }

//            $offerIds = [];
//            foreach ($result['rows'] as &$row) {
//                $offerIds = array_merge($offerIds, explode(',', trim($row['sOfferIds'], ',')));
//            }
//
//            $offerIds = array_unique($offerIds);
//            $userNameList = XhsysUser::getUserNameById($offerIds);
//            foreach ($result['rows'] as &$row) {
//                if ($row['sOfferIds']) {
//                    $ids    = trim($row['sOfferIds'], ',');
//                    $ids    = explode(',', $ids);
//                    $names  = [];
//                    foreach ($ids as $userId) {
//                        $names[] = $userNameList[$userId];
//                    }
//                    $row['sOfferUserName'] = implode(',', $names);
//                }
//            }
            Main::runUserNameById($result['rows'], ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
//            !$home and Main::runUserNameById($result['rows'], ['iLastModifyUserId' => 'iLastModifyUserId'], true);
            return $home ? ($this->request->isAjax() ? $this->sendJsonResponse($result['rows']) : $result['rows']) : $this->response->setJsonContent($result);
        } catch (\Exception $e) {
            if ($home) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 新建问题/需求
     *
     *
     * @return string
     * @throws \Helpers\XhException
     *
     * create by zqk 20181211
     */
    public function trackTaskFormAction()
    {
        $this->view->pick('track/trackTaskForm');
        Assets::UMEditor();
        Assets::UEditor();
        Assets::select2();
        Assets::easyUI('js/track/trackTaskForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $taskType = $this->request->getQuery('iType', 'int');
        $iTTd = $this->request->getQuery('iTTId', 'int', 0);
        $formButtonArr = [];
        $schoolArr = School::getPower(true);
        $schoolArr === true and $schoolArr = XhschoolInfo::getSchoolSupportArray();
        if (empty($iTTd)) {
            if ($this->checkOperatePower($taskType, 'Add')) {
                $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '提交'];
                $formButtonArr[] = ['id' => 'bt_form_reset', 'text' => '重置'];
            } else {
                return $this->sendViewError('无新增权限');
            }
        }

        if (!empty($iTTd)) {
            if ($this->checkOperatePower($taskType, 'Edit')) {
                $formButtonArr[] = ['id' => 'bt_form_edit', 'text' => '修改'];
            } else {
                return $this->sendViewError('无编辑权限');
            }
        }

        $formButtonArr[] = ['id' => 'bt_form_back', 'text' => '返回'];

        if ($taskType == 3) {
            $formName = 'XHTrack_Task_Res';
        } elseif ($taskType == 2) {
            $formName = 'XHTrack_Task_Question';
        } else {
            $formName = 'XHTrack_Task';
        }
        $this->view->setVars([
            'iTTd' => $iTTd,
            'Form' => Template::createForm($formName),
            'FormButton' => Template::createButtonToolBar($formButtonArr),
            'useful' => json_encode([
                'schoolArr' => $schoolArr,
                'stateArr' => $this->taskState[$taskType],
                'suppState' => $this->techSupportStatus,
//                'appArr'    => $this->getAppInfoArr($taskType),
                'appArr' => $this->getProducts(),
                'isTech' => in_array('TECH', Main::getLoginUserInfo('depTag')) || Main::getLoginUserInfo('logonName') == 'admin',
            ]),
        ]);
    }

    /**
     * 新增/修改跟踪问题
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170314
     * modify by ck 20170330    记录新增/修改日志
     */
    public function modifyTrackTaskDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        try {
            $data = Main::getRealData($this->request->getPost());
            $newSchoolId = isset($data['sSchoolId']) ? $data['sSchoolId'] : [];
            $data['sSchoolId'] = implode(',', $newSchoolId);
            $data['sSchoolId'] and $data['sSchoolId'] = ',' . $data['sSchoolId'] . ',';

            $newOfferIds = isset($data['sOfferIds']) ? $data['sOfferIds'] : [];
            $data['sOfferIds'] = implode(',', $newOfferIds);
            $data['sOfferIds'] and $data['sOfferIds'] = ',' . $data['sOfferIds'] . ',';

            $schoolNameData = XhschoolInfo::getSchoolSupportArray();
            if ($data['iTTId']) {
                $new = false;
                $taskModel = XhtrackTask::findFirst($data['iTTId']);
                $msg = [];
                $data['mRemarks'] != $taskModel->mRemarks and $msg[] = '修改备注：' . $data['mRemarks'];
                if ($data['sSchoolId'] != $taskModel->sSchoolId) {
                    $oldSchoolId = $taskModel->sSchoolId ? explode(',', trim($taskModel->sSchoolId, ',')) : [];
                    $addSchoolId = array_diff($newSchoolId, $oldSchoolId);
                    $delSchoolId = array_diff($oldSchoolId, $newSchoolId);
                    $addSchoolName = $delSchoolName = [];
                    foreach ($addSchoolId as $schId) {
                        $addSchoolName[] = $schoolNameData[$schId];
                    }
                    foreach ($delSchoolId as $schId) {
                        $delSchoolName[] = $schoolNameData[$schId];
                    }
                    $addSchoolName and $msg[] = '新增学校：' . implode(',', $addSchoolName);
                    $delSchoolName and $msg[] = '删除学校：' . implode(',', $delSchoolName);
                }
                $taskModel = XhtrackTask::createRecord($data, $taskModel);
                $msg and $this->dealChangeLog($taskModel, '修改信息', implode('<br />', $msg), '', 'info');
            } else {
                $new = true;
                if ($data['iType'] == 2) {
                    $data['iSupportState'] = 0;
                    $data['iState'] = 0;
                }
                $taskModel = XhtrackTask::createRecord($data);
                $schoolNameArr = [];
                foreach ($newSchoolId as $schoolId) {
                    $schoolNameArr[] = $schoolNameData[$schoolId];
                }
                $msg = [];
                $schoolNameArr and $msg[] = '学校：' . implode(',', $schoolNameArr);
                $taskModel->mRemarks and $msg[] = '备注：' . $taskModel->mRemarks;
                $this->dealChangeLog($taskModel, '创建任务', $msg ? implode('<br />', $msg) : '无学校及备注信息', '','info');
            }
//        $taskModel = XhtrackTask::createRecord($data);
//        $new = $taskModel->iTTId ? false : true;
            if (!$this->checkOperatePower($taskModel->iTaskType, $new ? 'Add' : 'Edit')) {
                return $this->sendErrorResponse('403', '无权限');
            };

            if ($data['assignUserId']) {
                $assign = new XhtrackTaskAssign();
                $assign->iTTId = $taskModel->iTTId;
                $assign->iUserId = $data['assignUserId'];
                $assign->iType = 1;
                $re = $assign->save();
                if (!$re) {
                    return $this->sendErrorResponse('500', '指派失败');
                }
                $userName = XhhrmStaff::findFirst([
                    'columns' => 'iStaffId,sStaffName',
                    'conditions' => "iUserId =". $data['assignUserId'],
                ]);
                if (!$userName) {
                    return $this->sendErrorResponse(500, '要指派的员工不存在');
                }
                $content = '指派任务到' . $userName->sStaffName;
                $this->dealChangeLog($taskModel, '指派任务', $content, '','info');
                if (empty($taskModel->iState)) {
                    $taskModel->iState = 32;
                }
            }
            if (!$taskModel->modifyData($new)) {
                return $this->sendErrorResponse('500', '保存失败');
            }
            Main::createCommitLog('track', 'Task', $new ? 'add' : 'edit', $taskModel, $taskModel->iTTId);


//            return $this->response->setContent('success');
            return $this->sendSuccessResponse('success');
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 更新任务状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170316
     * modify by ck 20170320    如不需要确认学校则直接改为已完成，增加修改日志
     * modify by ck 20170331    学校待确认阶stateChangeLog段不可修改状态
     * modify by ck 20170511    完成时如无学校则更新确认状态，切换到学校待确认则清空确认状态
     * modify by ck 20171020    创建状态更新记录
     * modify by zqk 20181016    创建状态更新记录
     */

    public function setTaskStateAction()
    {
        $taskType = $this->request->getPost('taskType', 'int');
        $taskIds = $this->request->getPost('ids', 'string');
        $taskState = $this->request->getPost('state', 'int');
        $planDate = $this->request->getPost('planDate', 'string');
        $explain = $this->request->getPost('explain', 'string');
        $solveVersion = $this->request->getPost('solveVersion', 'string');
        $taskIds = explode(',', $taskIds);
        if (!$taskIds || $taskState == '') {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        if ($taskState == 99 && $taskType != 3) {
            $explain = '解决版本：' . $solveVersion;
            if (!$solveVersion) {
                return $this->sendErrorResponse(400, '解决版本不能为空');
            }
        } else if (in_array($taskState, [30, 40, 50]) && (!$planDate || !$explain)) {
            return $this->sendErrorResponse(400, '计划完成时间或说明不能为空');
        } else if (!$explain) {
            return $this->sendErrorResponse(400, '说明不能为空');
        }
        try {
            $this->db->begin();
            foreach ($taskIds as $taskId) {
                if (!$this->checkOperatePower($taskType, 'Edit')) {
                    return $this->sendErrorResponse(400, '无操作权限');
                }
                $taskModel = XhtrackTask::findFirst($taskId);
                $oldState = $taskModel->iState;
                $power = '';
                if ($oldState == 1 || $this->getStateName($taskModel->iTaskType, $oldState) == '已发布') {
                    if (!$this->checkOperatePower(0, 'Restart')) {
                        return $this->sendErrorResponse(400, $this->getStateName($taskModel->iTaskType, $oldState) . '状态不可更改');
                    }
                    $taskModel->sConfirmId = [];
                    $taskModel->iConfirmState = null;
                    $power = 'danger';
                }
                $taskModel->iState = $taskState;
                $taskModel->tPlanFinishTime = $planDate ?: null;
                if (!$taskModel->sSchoolId && $this->getStateName($taskModel->iTaskType, $taskModel->iState) == '已发布') {
                    $taskModel->iState = 1;
                    $taskModel->iConfirmState = end($this->confirmState[$taskModel->iTaskType]);
                    $taskModel->tRealFinishTime = date('Y-m-d');
                }
                //新增日志
                $this->dealChangeLog($taskModel, '更改状态', $this->getStateName($taskModel->iTaskType, $oldState) . ' -> ' . $this->getStateName($taskModel->iTaskType, $taskModel->iState), $explain, $power);
                if (!$taskModel->save()) {
                    throw new \Exception('保存失败');
                }
                if ($taskModel->iState == 1 && $taskModel->sFeedbackId) {
                    $this->setFeedbackComplete($taskModel->sFeedbackId);
                }
                //新增记录
                $stateModel = new XhtrackTaskstate();
                $stateModel->iState = $taskState;
                $stateModel->iTTId = $taskModel->iTTId;
                $stateModel->sExplain = $explain;
                $stateModel->tPlanDate = $planDate;
                if (!$stateModel->save()) {
                    throw new \Exception('保存失败');
                }
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//        Main::createCommitLog('track', 'Task', 'changeState', ['iState' => $taskState, 'ids' => $taskIds], null, '批量更改');
        return $this->sendSuccessResponse('更改成功');
    }

    /**
     * 更改问题反馈开发状态
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181109
     * create by zqk 20181109
     */
    public function setProTaskStateAction()
    {
        $taskType = $this->request->getPost('taskType', 'int');
        if (!$this->checkOperatePower($taskType, 'TechState')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $taskIds = $this->request->getPost('ids', 'string');
        $taskState = $this->request->getPost('state', 'int');
        $planDate = $this->request->getPost('planDate', 'string');
        $explain = $this->request->getPost('explain', 'string');
        $reason = $this->request->getPost('reason', 'string');
        $sSolveWay = $this->request->getPost('sSolveWay', 'string');
        $solveVersion = $this->request->getPost('solveVersion', 'string');
        $taskIds = explode(',', $taskIds);
        $loginUserId = Main::getLoginUserInfo('userId');
        if (!$taskIds || $taskState == '' || $taskType != 2) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        if ($taskState == 99) {
            $explain = '解决版本：' . $solveVersion;
            if (!$solveVersion) {
                return $this->sendErrorResponse(400, '解决版本不能为空');
            }
        } elseif (in_array($taskState, [30, 40, 50]) && (!$planDate || !$explain)) {
            return $this->sendErrorResponse(400, '计划时间或说明不能为空');
        } elseif (in_array($taskState, [33, 37]) && (!$explain || !$reason)) {
            return $this->sendErrorResponse(400, '原因或说明不能为空');
        } elseif ($taskState == 38 && (!$planDate || !$explain || !$sSolveWay || !$reason)) {
            return $this->sendErrorResponse(400, '计划时间或解决方法或原因或说明不能为空');
        } elseif (!$explain) {
            return $this->sendErrorResponse(400, '说明不能为空');
        }
        try {
            $this->db->begin();
            foreach ($taskIds as $taskId) {
                $ifAssign = XhtrackTaskAssign::findFirst([
                    'columns' => 'iId,iUserId',
                    'conditions' => 'bDelete = 0 AND iType = 1 AND iTTId = ' . $taskId,
                    'order' => 'iId desc'
                ]);
                $taskModel = XhtrackTask::findFirst($taskId);
                if ($ifAssign) {
                    if ($loginUserId != $ifAssign->iUserId && !User::isAdmin()) {
                        return $this->sendErrorResponse(403, '非指派人无操作权限');
                    }
                } else {
                    if ($taskModel->iCreateUserId != $loginUserId && !User::isAdmin()) {
                        return $this->sendErrorResponse(403, '非创建人人无操作权限');
                    }
                }
                $oldState = $taskModel->iState;
                $power = '';
                if ($this->getStateName($taskModel->iTaskType, $taskModel->iSupportState) == '已发布' || $taskModel->iSupportState == 1) {
                    if (!$this->checkOperatePower(0, 'Restart')) {
                        return $this->sendErrorResponse(400, $this->getStateName($taskModel->iTaskType, $taskModel->iSupportState) . '状态不可更改');
                    }
                    $taskModel->sConfirmId = [];
                    $taskModel->iConfirmState = null;
                    $power = 'danger';
                }
                $taskModel->iState = $taskState;
                $taskModel->tPlanFinishTime = $planDate ?: null;
                if (!$taskModel->sSchoolId && $this->getStateName($taskModel->iTaskType, $taskModel->iSupportState) == '已发布') {
                    $taskModel->iSupportState = 1;
                    $taskModel->iConfirmState = end($this->confirmState[$taskModel->iTaskType]);
                    $taskModel->tRealFinishTime = date('Y-m-d');
                }
                //新增日志
                $this->dealChangeLog($taskModel, '更改状态', $this->getStateName($taskModel->iTaskType, $oldState) . ' -> ' . $this->getStateName($taskModel->iTaskType, $taskModel->iState), $explain, $power);
                if ($taskState == 35 || $taskState == 36) {
                    $taskModel->iSupportState = 8;
                } elseif ($taskState == 99) {
                    $taskModel->iSupportState = 9;
                    $taskModel->sVersion = $solveVersion;
                } elseif ($taskState == 38) {
                    $taskModel->sSolveWay = $sSolveWay;
                    $taskModel->sReason = $reason;
                }
                if (!$taskModel->save()) {
                    throw new \Exception('保存失败');
                }
                if ($taskModel->iState == 1 && $taskModel->sFeedbackId) {
                    $this->setFeedbackComplete($taskModel->sFeedbackId);
                }
                //新增记录
                $stateModel = new XhtrackTaskstate();
                $stateModel->iState = $taskState;
                $stateModel->iTTId = $taskModel->iTTId;
                $stateModel->sExplain = $explain;
                $stateModel->tPlanDate = $planDate;
                if (!$stateModel->save()) {
                    throw new \Exception('保存失败');
                }
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//        Main::createCommitLog('track', 'Task', 'changeState', ['iState' => $taskState, 'ids' => $taskIds], null, '批量更改');
        return $this->sendSuccessResponse('更改成功');
    }

    /**
     * 更改问题反馈技术支持状态
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181109
     * create by zqk 20181109
     */
    public function setSuppTaskStateAction()
    {
        $taskType = $this->request->getPost('taskType', 'int');
        if (!$this->checkOperatePower($taskType, 'SuppState')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $taskIds = $this->request->getPost('ids', 'string');
        $taskState = $this->request->getPost('state', 'int');
        $explain = $this->request->getPost('explain', 'string');
        $taskIds = explode(',', $taskIds);
        $loginUserId = Main::getLoginUserInfo('userId');
        if (!$taskIds || !in_array($taskState, array_keys($this->techSupportStatus)) || $taskType != 2) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        if (!$explain) {
            return $this->sendErrorResponse(400, '说明不能为空');
        }
        try {
            $this->db->begin();
            foreach ($taskIds as $taskId) {
                $taskModel = XhtrackTask::findFirst($taskId);
                $ifAssign = XhtrackTaskAssign::findFirst([
                    'columns' => 'iId,iUserId',
                    'conditions' => 'bDelete = 0 AND iType = 2 AND iTTId = ' . $taskId,
                    'order' => 'iId desc'
                ]);
                if ($ifAssign) {
                    if ($loginUserId != $ifAssign->iUserId && !User::isAdmin()) {
                        return $this->sendErrorResponse(403, '非指派人无操作权限');
                    }
                } else {
                    if ($taskModel->iCreateUserId != $loginUserId && !User::isAdmin()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '非创建人不能指派该任务');
                    }
                }

                $oldState = $taskModel->iSupportState;
                $power = '';
                if ($taskModel->iSupportState == 1) {
                    if (!$this->checkOperatePower(0, 'Restart')) {
                        return $this->sendErrorResponse(400, '任务已完成');
                    }
                    $taskModel->sConfirmId = [];
                    $taskModel->iConfirmState = null;
                    $power = 'danger';
                }
                $taskModel->iSupportState = $taskState;
//                if (in_array($taskState, [0, 7])) {
//                    $taskModel->iState = 32;
//                }
                if (!$taskModel->sSchoolId) {
//                    $taskModel->iSupportState = 1;
                    $taskModel->iConfirmState = end($this->confirmState[$taskModel->iTaskType]);
                    $taskModel->tRealFinishTime = date('Y-m-d');
                }
                //新增日志
                $this->dealChangeLog($taskModel, '更改状态', $this->getStateName($taskModel->iTaskType, $oldState) . ' -> ' . $this->getStateName($taskModel->iTaskType, $taskModel->iSupportState), $explain, $power);
                if (!$taskModel->save()) {
                    throw new \Exception('保存失败');
                }
                if ($taskModel->iSupportState == 1 && $taskModel->sFeedbackId) {
                    $this->setFeedbackComplete($taskModel->sFeedbackId);
                }
                //新增记录
                $stateModel = new XhtrackTaskstate();
                $stateModel->iState = $taskState;
                $stateModel->iTTId = $taskModel->iTTId;
                $stateModel->sExplain = $explain;
                if (!$stateModel->save()) {
                    throw new \Exception('保存失败');
                }
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//        Main::createCommitLog('track', 'Task', 'changeState', ['iState' => $taskState, 'ids' => $taskIds], null, '批量更改');
        return $this->sendSuccessResponse('更改成功');
    }

    /**
     * 学校确认页面
     *
     * create by ck 20170317
     * modify by ck 20170330    从表更改为字段
     * modify by ck 20170511    去除复选框，改为下拉，并设置默认值
     */
    public function schoolTaskConfirmAction()
    {
        $this->view->pick('track/schoolTaskConfirm');
        Assets::importJs('js/track/schoolTaskConfirm.js');
        $taskId = $this->request->getQuery('iTTId', 'int');
        $this->checkOperatePower(0, 'Confirm') or die('无操作权限！');
        $taskModel = XhtrackTask::findFirst("iTTId = {$taskId} and bDelete = 0");
        if ($taskModel->iTaskType == 2) {
            if (isset($this->techSupportStatus[$taskModel->iSupportState])) {
                if ($this->techSupportStatus[$taskModel->iSupportState] != '解决') {
                    die('非待确认阶段!');
                }
            } else {
                die('非待确认阶段!');
            }
        } else {
            @$this->taskState[$taskModel->iTaskType][$taskModel->iState] == '已发布' or die('非待确认阶段!');
        }
        $taskModel or die('无对应记录！');
        $taskModel->sSchoolId or die('无需确认！');
        $schoolArr = [];
        $schoolNameArr = XhschoolInfo::getSchoolSupportArray();
        foreach (explode(',', trim($taskModel->sSchoolId, ',')) as $schoolId) {
            $schoolArr[$schoolId] = ['iSchoolId' => $schoolId, 'sSchoolName' => $schoolNameArr[$schoolId]];
        }
        isset($this->confirmState[$taskModel->iTaskType]) and $this->view->setVar('confirmStateArr', $this->confirmState[$taskModel->iTaskType]);
//        $schoolConfirm = $taskModel->sConfirmId ? explode(',', trim($taskModel->sConfirmId, ',')) : [];

        //处理原先选择，设置默认值
        $defaultState = [];
//        foreach($schoolConfirm as $school) {
//            $school = explode(':', $school);
//            isset($school[1]) and $defaultState['confirmState[' . $school[0] . ']'] = $school[1];
//        }
        foreach ((array)$taskModel->sConfirmId as $schId => $state) {
            $defaultState["confirmState[{$schId}]"] = $state;
        }
        $this->tag->setDefaults($defaultState);
        $this->view->setVars([
            'schoolArr' => $schoolArr,
            'taskId' => $taskId
        ]);
    }

    /**
     * 确认学校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170317
     * modify by ck 20170330    更改学校确认位置及日志
     * modify by ck 20170420    添加备注修改
     * modify by ck 20170511    确认逻辑更改
     */
    public function confirmTaskSchoolAction()
    {
        $this->view->disable();
        $this->checkOperatePower(0, 'Confirm') or die('无操作权限！');
        $taskId = $this->request->getQuery('taskId', 'int');
        $remark = $this->request->getPost('mRemarks', 'string');
        $newConfirmSchool = $this->request->getPost('confirmState', 'int', []);
        $schoolNameArr = XhschoolInfo::getSchoolSupportArray();
        $taskModel = XhtrackTask::findFirst("iTTId = {$taskId} and bDelete = 0");
        $msg = [];
        $complete = true;
        $confirmCount = 0;

        //处理原学校确认状态
//        $oldConfirmSchool = [];
//        $confirmSchool = $taskModel->sConfirmId ? explode(',', trim($taskModel->sConfirmId, ',')) : [];
//        foreach($confirmSchool as $info){
//            $info = explode(':', $info);
//            $oldConfirmSchool[$info[0]] = isset($info[1]) ? $info[1] : '';
//        }

        //对比原信息差异
        foreach ($newConfirmSchool as $schId => $state) {
            if ($state) {
                //不为空则计数+1，最终确认为最小值（0除外）
                $confirmCount++;
                if ($taskModel->iConfirmState == 0) {
                    $taskModel->iConfirmState = $state;
                } elseif ($state < $taskModel->iConfirmState) {
                    $taskModel->iConfirmState = $state;
                }
            } else {
                //为空则标记为未完成
                $complete = false;
            }
//            $oldState = isset($oldConfirmSchool[$schId]) ? $oldConfirmSchool[$schId] : 0;
            $oldState = isset($taskModel->sConfirmId[$schId]) ? $taskModel->sConfirmId[$schId] : 0;
            if ($state == $oldState) {
                continue;
            }
            $msg[] = $schoolNameArr[$schId] . '：'
                . $this->getConfirmStateName($taskModel->iTaskType, $oldState)
                . ' -> '
                . $this->getConfirmStateName($taskModel->iTaskType, $state);
        }
        if (empty($msg)) {
            return $this->sendErrorResponse(500, '无变动!');
        }
        if ($complete) {
            if ($taskModel->iTaskType == 2) {
                $taskModel->iSupportState = 1;
            } else {
                $taskModel->iState = 1;
            }

            $taskModel->tRealFinishTime = date('Y-m-d');
        }
        if ($remark) {
            $taskModel->mRemarks = $remark;
            $msg[] = '修改备注：' . $remark;
        }
        $this->dealChangeLog($taskModel, '学校确认(' . $confirmCount . '/' . count($newConfirmSchool) . ')', implode('<br />', $msg), $remark,'success');


        //处理确认内容并保存
        $taskModel->sConfirmId = $newConfirmSchool;
//        $confirmSchool = [];
//        foreach($newConfirmSchool as $schId => $state){
//            $confirmSchool[] = $schId . ':' . $state;
//        }
//        $taskModel->sConfirmId = implode(',', $confirmSchool);

        if (!$taskModel->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        if ($taskModel->iState == 1 && $taskModel->sFeedbackId) {
            $this->setFeedbackComplete($taskModel->sFeedbackId);
        }
        Main::createCommitLog('track', 'taskSchool', 'confirm', $newConfirmSchool, $taskId);
        return $this->sendSuccessResponse('确认成功');
    }

    /**
     * 查看变更日志
     *
     * create by ck 20170320
     * modify by ck 20170511    使用预处理
     * modify by ck 20170725    可输入备注
     * modify by ck 20171020    添加状态变更日志
     */
    public function stateChangeLogAction()
    {
        $taskId = $this->request->getQuery('taskId', 'int');
        if (!$this->checkOperatePower(0)) {
            return $this->sendViewError('无查看权限');
        }
        $this->view->pick('track/stateChangeLog');
        Assets::importJs('js/track/stateChangeLog.js');
        $viewValues = [];

        //操作日志
        $task = XhtrackTask::findFirst($taskId);
        $viewValues['commitLog'] = $task->mStateLog;

        //可输入备注
        if ($this->checkOperatePower($task->iTaskType, 'Edit')) {
            $viewValues['allowMark'] = true;
        }

        //状态变更日志
        $states = XhtrackTaskstate::find([
            'columns' => 'iState,tCreateDate,sExplain,tPlanDate,iCreateUserId',
            'conditions' => 'iTTId = :ttId:',
            'bind' => ['ttId' => $taskId],
            'order' => 'iTSId DESC'
        ])->toArray();
        foreach ($states as &$state) {
            $state['iState'] = $this->getStateName($task->iTaskType, $state['iState']);
        }
        Main::runUserNameById($states, 'iCreateUserId', true);
        $viewValues['stateLog'] = $states;
        $viewValues['iTaskType'] = $task->iTaskType;

        return $this->view->setVars($viewValues);
    }

    /**
     * 设置新备注
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170725
     */
    public function setTaskRemarkAction()
    {
        $taskId = $this->request->getPost('taskId', 'int');
        $remark = $this->request->getPost('remark', 'string');
        if (!$taskId && !$remark) {
            return $this->sendErrorResponse(400, '缺少必要参数！');
        }
        $task = XhtrackTask::findFirst($taskId);
        if (!$task) {
            return $this->sendErrorResponse(500, '无该记录信息！');
        }
        if (!$this->checkOperatePower($task->iTaskType, 'Edit')) {
            return $this->sendErrorResponse(403, '无操作权限！');
        }
        $task->mRemarks = $remark;
        $this->dealChangeLog($task, '修改备注', $remark);
        if (!$task->save()) {
            return $this->sendErrorResponse(500, '保存失败！');
        }
        return $this->sendSuccessResponse('保存成功！');
    }

    /**
     * 删除任务（单个）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170401
     */
    public function delTaskRecordAction()
    {
        $this->view->disable();
        $idArr = explode(',', $this->request->getPost('ids', 'int'));
        XhtrackTask::deleteRecordById($idArr) or die('删除失败！');
        Main::createCommitLog('track', 'task', 'del', ['ids' => $idArr], null, '单个删除');
        return $this->response->setContent('删除成功！');
    }

    /**
     * 上传图片
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171017
     */
    public function uploadImageAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendJsonResponse(['state' => '缺少文件']);
        }
        $file = $this->request->getUploadedFiles()[0];
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $fileName = $file->getName();
        $fullPath = $filePath . $fileName;
        if (!is_writable($filePath)) {
            return $this->sendJsonResponse(['state' => $filePath . '缓存无写入权限']);
        }
        $file->moveTo($fullPath);
        $result = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
        @unlink($fullPath);
        if (!$result) {
            return $this->sendJsonResponse(['state' => '上传失败']);
        }
        return $this->response->setJsonContent([
            'name' => basename($result),
            'originalName' => $fileName,
            'size' => $file->getSize(),
            'state' => 'SUCCESS',
            'type' => $file->getExtension(),
            'url' => $result
        ]);//->setContentType('text/html');
    }

    /**
     * 首页展示窗体
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171018
     */
    public function homeAction()
    {
        $this->view->pick('track/home');
        $trackRows = [];
        try {
            foreach ($this->taskType as $type => $name) {
                if (!$this->checkOperatePower($type)) {
                    continue;
                }
                $trackRows[$type] = [
                    'name' => $name,
                    'rows' => $this->getTrackTaskDataAction(true, $type)
                ];
            }
            if (!$trackRows) {
                throw new \Exception('无查看权限');
            }
            return $this->view->setVar('trackRows', $trackRows);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 选择学校提问人页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20171019
     */
    public function schoolOfferAction()
    {
        $this->view->pick('track/schoolOffer');
        Assets::easyUI('js/track/schoolOffer.js');
        $schoolIds = $this->request->getQuery('schoolIds', 'string');
        if (!$schoolIds) {
            return $this->sendViewError('缺少学校id');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => '姓名：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'login_name', 'label' => ' 登录名：'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'Track_SchoolOffer', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr),
            ])
        ]);
    }

    /**
     * 根据学校id获取该学校学生教师列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171020
     */
    public function getSchoolOfferAction()
    {
        $searchArr = $this->request->get('search');
        $schoolIds = $this->request->getPost('schoolIds', 'string');
        if (!$schoolIds) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }

        $parameters = [
            'columns' => 'iUserId,sLogonName,sUserName,iSchoolId,iUserType',
            'conditions' => "bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iSchoolId IN ({$schoolIds}) AND iUserType IN (1,4)",
        ];
        Main::runSearchVagueConditions($parameters['conditions'], ['sUserName']);
        Main::runSearchVagueConditions($parameters['conditions'], ['sLogonName'], ['vague' => $searchArr['sLogonName']]);
        $result = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters, ['iUserType' => [1 => '学生', 4 => '教师']]);
        Main::runSchoolNameByIdStr($result['rows'], ['iSchoolId' => 'sSchoolName']);
        return $this->sendJsonResponse($result);
    }

    /**
     * 根据id获取任务详情
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171020
     */
    public function getTaskInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $info = XhtrackTask::findFirst($id);
        if (!$info) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        if (trim($info->sOfferIds, ',')) {
            $userNames = XhsysUser::find([
                'columns' => 'sUserName',
                'conditions' => 'bDelete = 0 AND iUserId IN ({idArr:array})',
                'bind' => ['idArr' => explode(',', trim($info->sOfferIds, ','))]
            ])->toArray();
            $userNames = array_column($userNames, 'sUserName');
            $info->sOfferUserName = implode(',', $userNames);
        }
        return $this->sendJsonResponse($info);
    }

    /**
     * 标记反馈解决状态
     *
     * @param $feedbackId
     * @return bool
     * @throws \Exception
     *
     * create by ck 20171218
     */
    private function setFeedbackComplete($feedbackId)
    {
        $url = Main::getConfigByName('feedback')['url'];
        if (!$url) {
            throw new \Exception('缺少反馈url');
        }
        $httpClient = new HttpClient($url);
        $response = $httpClient->patchJson('/api/v1/manage/feedback/solveStatus', [
            'feedbackIdList' => [$feedbackId],
            'operatorId' => Main::getLoginUserInfo('userId'),
            'operatorName' => Main::getLoginUserInfo('userName'),
            'solveStatus' => 1
        ]);
        if (!$response->isSuccess()) {
            throw new \Exception('反馈请求失败：' . json_encode($response));
        }
        return true;
    }

    /**
     * 获取应用列表
     *
     *
     * @return array
     * @throws \Helpers\XhException
     *
     * create by zqk 20180627
     */
    private function getProducts()
    {
        if (User::isAdmin()) {
            $apps = XhpmProduct::find([
                'columns' => 'iId,sName,iType',
                'conditions' => 'bDelete = 0',
            ])->toArray();
        } else {
            $productIds = Power::getextrapower('product', 'productList');  //获取扩展部门权限
            if ($productIds === true) {
                $apps = XhpmProduct::find([
                    'columns' => 'iId,sName,iType',
                    'conditions' => 'bDelete = 0',
                ])->toArray();
            } else {
                $apps = $this->modelsManager->createBuilder()
                    ->columns('iId,sName,iType')
                    ->from('Admin\Models\pm\XhpmProduct')
                    ->where('bDelete = 0')
                    ->inWhere('iId', $productIds)
                    ->getQuery()
                    ->execute()
                    ->toArray();
            }
        }
        $datas = [];
        $productTypes = self::$productTypes;
        foreach ($apps as $k => $app) {
            $datas[$k]['id'] = $app['iId'];
            if (empty($app['iType'])) {
                $datas[$k]['text'] = $app['sName'];
            } else {
                $datas[$k]['text'] = $app['sName'] . '(' . $productTypes[$app['iType']] . ')';
            }
        }
        $datas = array_column($datas, 'text', 'id');
        return $datas;
    }

    /**
     * 获取所有员工
     *
     *
     * @return array
     *
     * create by zqk 20190125
     */
    private function getAllStaff()
    {
        $data = [];
        $uIds = Hrm::getUserWithDepName();
        foreach ($uIds as $k => $uId) {
            if (!empty($k)) {
                $data[$k] = $uId;;
            }
        }
        return $data;
    }



    /**
     * 获取上报人Id(运营 教学 form)
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     * create by zqk 20181011
     * modify by zqk 20181031
     */
    public function getReportUserIdAction()
    {
        $yyData = [];
        $jxData = [];
        $yyUids = Hrm::getDepStaffByTag('XHYYB');
        $jxUids = Hrm::getDepStaffByTag('XHJXB');
        foreach ($yyUids as $k => $yyUid) {
            $yyData[$k]['id'] = $k;
            $yyData[$k]['text'] = '运营部' . '-' . $yyUid;
        }
        foreach ($jxUids as $k => $jxUid) {
            $jxData[$k]['id'] = $k;
            $jxData[$k]['text'] = '教学部' . '-' . $jxUid;
        }
        $data = array_merge($yyData, $jxData);
        return $this->sendJsonResponse($data);
    }

    /**
     * 获取指派人Id(技术部门)
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20190125
     */
    public function getAssignUserIdAction()
    {
        $data = [];
        $jsUids = Hrm::getDepStaffByTag('XHJSB');
        foreach ($jsUids as $k => $jsUid) {
            $data[$k]['id'] = $k;
            $data[$k]['text'] = '技术部' . '-' . $jsUid;
        }
        return $this->sendJsonResponse(array_values($data));
    }

    /**
     * 指派任务
     *
     *
     * @return string
     *
     * create by zqk 20181012
     */
    public function assignTaskAction()
    {
        if (!Power::exist('Track_BUG_Assign')) {
            return $this->sendViewError('无指派权限');
        }
        $iTTId = $this->request->getQuery('iTTId', 'int');//问题Id
        $iType = $this->request->getQuery('iType', 'int');//问题Id
        if (!$iTTId || !$iType) {
            return $this->sendViewError('参数错误');
        }
        $this->view->pick('track/assignTask');
        Assets::easyUI();
        Assets::importJs('js/track/assignTask.js');
        $taskSearchArr[] = ['type' => 'text', 'id' => 'staffName', 'label' => ' 姓名: '];
        $taskSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $this->view->setVars([
            'iTTId' => $iTTId,
            'iType' => $iType,
            'assignTask' => Template::createList('assignTask', 'assignTask', [
                'searchToolbar' => Template::createSearchToolBar($taskSearchArr),
            ]),
        ]);
    }


    /**
     * 获取部门列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180412
     */
    public function getDepartmentsAction()
    {
        try {
            $deps = XhhrmDepart::find([
                'columns' => 'iDepId,sDepName',
                'conditions' => 'bDelete = 0 And iParentId = 0'
            ])->toArray();
            foreach ($deps as $k => $dep) {
                $depId = $dep['iDepId'];
                $children = $this->getDepChildren($depId);
                if (!empty($children)) {
                    $deps[$k]['iconCls'] = 'fa-file-folder';
                    $deps[$k]['children'] = $children;
                    $deps[$k]['state'] = "closed";
                } else {
                    $deps[$k]['iconCls'] = 'fa-file-text';
                }
            }
            return $this->sendJsonResponse($deps);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());

        }
    }

    /**
     * 获取部门子部门
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180523
     */
    private function getDepChildren($id)
    {
        $deps = XhhrmDepart::find([
            'columns' => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 And iParentId = ' . $id,
        ])->toArray();
        foreach ($deps as $k => $dep) {
            $depId = $dep['iDepId'];
            $children = $this->getDepChildren($depId);
            if (!empty($children)) {
                $deps[$k]['iconCls'] = 'fa-file-folder';
                $deps[$k]['children'] = $children;
                $deps[$k]['state'] = "closed";
            } else {
                $deps[$k]['iconCls'] = 'fa-file-text';
            }
        }
        return $deps;
    }

    /**
     * 获取部门员工
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180830
     */
    public function getStaffAction()
    {
        $iDepId = $this->request->getPost('iDepId', 'int', 0);
        $sStaffName = $this->request->getPost('sStaffName');
        $condition = "bDelete = 0 and iStaffStatus = 1";
        $condition .= $iDepId ? " AND sDepIds like '%$iDepId%'" : '';
        $condition .= $sStaffName ? " AND sStaffName like '%$sStaffName%'" : '';
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns("sStaffName,iUserId")
                ->addFrom('Admin\Models\hrm\XhhrmStaff')
                ->where($condition);
            $data = Main::runBuilderPaginator($builder, true);
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 指派
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181016
     */
    public function assignAction()
    {
        $iTTId = $this->request->getPost('iTTId');
        $iType = $this->request->getPost('iType');
        $userId = $this->request->getPost('userId');
        if (!$iTTId) {
            return $this->sendErrorResponse(400, '请选择要指派的任务');
        }
        if (!$userId) {
            return $this->sendErrorResponse(400, '请选择要指派的人');
        }
        if (!in_array($iType, [1, 2])) {
            return $this->sendErrorResponse(400, '请选择指派的类型');
        }
        $loginUserId = Main::getLoginUserInfo('userId');

        if ($iType == 1) {
            if (!Power::exist('Track_BUG_Assign')) {
                return $this->sendErrorResponse(403, '无指派权限');
            }
        }
        if ($iType == 2) {
            if (!Power::exist('Track_BUG_Move')) {
                return $this->sendErrorResponse(403, '无指派权限');
            }
        }
        try {
            $this->db->begin();
            $taskModel = XhtrackTask::findFirst($iTTId);
            if (!$taskModel) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '要指派的任务不存在');
            }
            $ifAssign = XhtrackTaskAssign::findFirst([
                'columns' => 'iId,iUserId',
                'conditions' => 'bDelete = 0 AND iTTId = ' . $iTTId,
                'order' => 'iId desc'
            ]);
            if ($ifAssign) {
                if ($loginUserId != $ifAssign->iUserId && !User::isAdmin()) {
                    return $this->sendErrorResponse(403, '非指派人无操作权限');
                }
            } else {
                if ($taskModel->iCreateUserId != $loginUserId && !User::isAdmin()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '非创建人不能指派该任务');
                }
            }
            $userName = XhhrmStaff::findFirst([
                'columns' => 'iStaffId,sStaffName',
                'conditions' => "iUserId = $userId",
            ]);
            if (!$userName) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '要指派的员工不存在');
            }
            $content = '指派任务到' . $userName->sStaffName;
            $this->dealChangeLog($taskModel, '指派任务', $content, '','info');
            if (empty($taskModel->iState)) {
                $taskModel->iState = 32;
            }
            $res = $taskModel->modifyData(false);
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '指派失败');
            }
            $assign = new XhtrackTaskAssign();
            $assign->iTTId = $iTTId;
            $assign->iUserId = $userId;
            $assign->iType = $iType;
            $re = $assign->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '指派失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('指派成功');
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 导出
     *
     *
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181019
     */
    public function exportProblemDataAction()
    {
        $this->view->disable();
        $taskType = $this->request->get('taskType', 'int');
        $startDate = $this->request->get('startDate', 'string');
        $endDate = $this->request->get('endDate', 'string');
        $state = $this->request->get('state', 'int');
        $confirmState = $this->request->get('confirmState', 'int');
        $vague = $this->request->get('vague', 'string');
        $schoolName = trim($this->request->get('schoolName', 'string'));
        $schoolId = $this->request->get('schoolId', 'int');
        $iReportUserId = $this->request->get('iReportUserId', 'int');
        $iProductId = $this->request->get('iProductId');
        $proName = $this->request->get('proName');
        $creatorId = $this->request->getPost('creatorId');
        $userId = $this->request->get('userId', 'int');
        $loginUserId = Main::getLoginUserInfo('userId');
        $params = [
            "taskType" => $taskType,
            "startDate" => $startDate,
            "endDate" => $endDate,
            "state" => $state,
            "confirmState" => $confirmState,
            "vague" => $vague,
            "schoolName" => $schoolName,
            "schoolId" => $schoolId,
            "iReportUserId" => $iReportUserId,
            "iProductId" => explode(',', $iProductId),
            "proName" => explode(',', $proName),
            "userId" => $userId,
            "loginUserId" => $loginUserId,
            "creatorId" => explode(',', $creatorId),
        ];
        try {
            $datas = $this->getProTrackTaskData($params, true);
            $title = [
                'sTaskName' => '问题名称',
                'sTaskContent' => '问题内容',
                'tOfferTime' => '提问时间',
                'tRealFinishTime' => '运营确认时间',
                'sSchoolName' => '提问学校',
                'mRemarks' => '备注',
                'iSupportState' => '处理状态',
//                'sSolveVersion' => '解决版本',
                'sOfferUserName' => '提问人',
                'sAppName' => '产品名称',
                'sName' => '问题类型',
                'iReportUserName' => '上报人',           //
                'iProLevel' => '问题等级',          //
                'iCreateUserName' => '记录人',
                'iState' => '问题状态',//
                'sReason' => '原因',       //
                'sSolveWay' => '解决方法',       //
                'sVersion' => '版本',       //
            ];
            $data = [];
            foreach ($datas as $v) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($v, $filed);
                }
                $data[] = $row;
            }
            $fileName = '问题反馈表';
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', ['header' => ['title' => '问题反馈表', 'width' => '300']]);
            return true;
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 问题反馈分类管理
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     * create by gby 20180925
     */
    public function classifyListAction()
    {
        if (!Power::exist('TrackClassify')) {
            return $this->sendErrorResponse(403, '抱歉，您没有查看此页面的权限！');
        }
        Assets::sweetAlert2();
        Assets::easyUI();
        Main::showNavPosition();
        $this->view->pick('track/classifyList');
        Assets::importJs('js/track/trackClassify.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        return $this->view->setVars([
            'Edit' => Power::exist('TrackClassify_Edit'),
            'Add' => Power::exist('TrackClassify_Add'),
            'Del' => Power::exist('TrackClassify_Del')
        ]);
    }

    /**
     * 获取所有分类信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by gby 20180925
     */
    public function getClassifyAction()
    {
        if (!Power::exist('TrackClassify')) {
            return $this->sendErrorResponse(403, '无权限操作');
        }
        $id = $this->request->getPost('id', 'int');
        if ($id) {
            // 获取子集
            return json_encode($this->recursionForArray($id));
        }
        $parameters = [
            'conditions' => "bDelete=:bDelete: AND iType=:iType: AND iParentId=:parentId: ",
            'bind' => ['parentId' => 0, 'bDelete' => 0, 'iType' => 2],
        ];
        $objs = Main::runModelPage('\\Admin\\Models\\sys\\XhsysClassification', $parameters);
        $array = $objs['rows'];
        Main::runUserName($array, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId']);
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray['rows'][$key] = $value;
            $newArray['rows'][$key]['children'] = $this->recursionForArray($value['id']);
            if ($newArray['rows'][$key]['children']) {
                $newArray['rows'][$key]['state'] = "closed";
            }
        }
        $newArray['total'] = $objs['total'];
        return $this->sendJsonResponse($newArray);
    }

    /**
     * 获取分类详情
     * @return string
     * create by gby 20180925
     */
    public function getClassifyInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XhsysClassification::findFirst($id);
        $jsonArray = $obj->toArray();
        if ($jsonArray['iParentId'] == 0) {
            $jsonArray['inputPareName'] = '顶层';
        } else {
            $pObj = XhsysClassification::findFirst($jsonArray['iParentId']);
            $jsonArray['inputPareName'] = $pObj->sName;
        }
        return json_encode($jsonArray);
    }

    /**
     * 分类下拉列表  id ,text easyui
     * @return string
     * created by gby 20180925
     */
    public function getClassifyEnumAction()
    {
//        $newArray[0]['id'] = 0;
//        $newArray[0]['text'] = '';
        $newArray = $this->selectRecursion(0);
        return json_encode($newArray);
    }

    /**
     * 搜索下拉框
     * @return string
     */
    public function getSearchEnumAction()
    {
        return json_encode($this->selectRecursion(0));
    }

    /**
     * 添加分类页面
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     * create by gby 20180925
     */
    public function addClassifyAction()
    {
        if (!Power::exist('TrackClassify_Add')) {
            return $this->sendErrorResponse(403, '无权限操作');
        }
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('../customer/js/myMain.js');
        Assets::easyUI('js/track/trackAddClassify.js');
        return $this->view->pick('track/classifyForm');
    }

    /**
     * 保存分类信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by 20180925
     */
    public function saveClassifyAction()
    {
        $data = $this->request->getPost();
        $id = $this->request->getPost('id', 'int');
        $sTag = $this->request->getPost('sTag', 'string');
        $iParentId = $this->request->getPost('iParentId', 'int');
        $parameters = [
            'conditions' => 'bDelete = 0 AND iType=:iType:',
            'bind' => ['iType' => 2]
        ];
        if ($id) {
            if (!Power::exist('TrackClassify_Edit')) {
                return $this->sendErrorResponse(403, '无操作权限');
            }
        } else {
            if (!Power::exist('TrackClassify_Add')) {
                return $this->sendErrorResponse(403, '无操作权限');
            }
        }
        if (!$data['sName']) {
            return $this->sendErrorResponse(400, '分类名称不能为空！');
        }
        if (!$iParentId) {
            if (!$sTag) {
                return $this->sendErrorResponse(400, '分类标签不能为空！');
            }
        }
        try {
            // 新增分类
            if (!$id) {
                // 判断分类名称是否存在
                if ($data['sName']) {
                    $parameters['conditions'] .= " AND sName = :sName:";
                    $parameters['bind'] += ['sName' => $data['sName']];
                    $sName = XhsysClassification::findFirst($parameters);
                    if ($sName) {
                        return $this->sendErrorResponse(400, '分类名称已存在,请重新输入');
                    }
                }
                // 判断分类标签是否存在
                if ($sTag) {
                    $parameters['conditions'] .= " AND sTag = :sTag:";
                    $parameters['bind'] += ['sTag' => $sTag];
                    $stag = XhsysClassification::findFirst($parameters);
                    if ($stag) {
                        return $this->sendErrorResponse(400, '分类标签已存在,请重新输入');
                    }
                }
                $data['iType'] = 2;
                $obj = new XhsysClassification();
            } else {
                // 修改分类
                $obj = XhsysClassification::findFirst($id);
            }
            $obj->assign($data);
            if ($sTag == '') {
                $obj->sTag = null;
            } else {
                $obj->sTag = (strtoupper(trim($sTag)));
            }
            if ($iParentId == '') {
                $obj->iParentId = 0;
            } else {
                $obj->iParentId = $iParentId;
            }
            $result = $obj->save();
            if ($result) {
                if ($id) {
                    return $this->sendSuccessResponse('修改成功');
                } else {
                    return $this->sendSuccessResponse('保存成功');
                }
            } else {
                if ($id) {
                    return $this->sendErrorResponse(500, '修改失败');
                } else {
                    return $this->sendErrorResponse(500, '添加失败');
                }
            }
        } catch (Exception $e) {
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

    /**
     * 删除分类
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by gby 20180926
     */
    public function deleteClassifyAction()
    {
        if (!Power::exist('TrackClassify_Del')) {
            return $this->sendErrorResponse(403, '无删除权限');
        }
        $id = $this->request->getPost('id', 'int');
        $obj = XhsysClassification::findFirst($id);
        $obj->bDelete = 1;
        $result = $obj->save();
        if ($result && $this->recursionForDelete([$id])) {
            return $this->sendSuccessResponse('删除成功');
        } else {
            return $this->sendErrorResponse(400, '删除失败');
        }
    }

    /**
     * 获取分类数据，列表树形展示
     * @param $parentId
     * @return array
     * create by gby 20180926
     */
    public function recursionForArray($parentId)
    {
        $parameters = [
            'conditions' => "bDelete=:bDelete: AND iType=:iType: AND iParentId=:parentId: ",
            'bind' => ['parentId' => $parentId, 'bDelete' => 0, 'iType' => 2],
        ];
        $objs = XhsysClassification::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        Main::runUserName($array, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId']);
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key] = $value;
            $newArray[$key]['children'] = $this->recursionForArray($value['id']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 分类下拉菜单 树型展示
     * @param $parentId
     * @return array
     * create by gby 20180926
     */
    public function selectRecursion($parentId)
    {
        $parameters = [
            'conditions' => "bDelete = :bDelete: AND iType = :iType: AND iParentId = :parentId: ",
            'bind' => ['parentId' => $parentId, 'bDelete' => 0, 'iType' => 2],
        ];
        $objs = XhsysClassification::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id'] = $value['id'];
            $newArray[$key]['text'] = $value['sName'];
            $newArray[$key]['children'] = $this->selectRecursion($value['id']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 删除当前类下的所有子类
     * @param $array
     * @return bool
     * created by gby 20180926
     */
    public function recursionForDelete($array)
    {
        $objs = XhsysClassification::find([
            'conditions' => 'iParentId in ({ids:array}) AND bDelete=:bDelete: ',
            'bind' => ['ids' => $array, 'bDelete' => 0]
        ]);
        $ids = [];
        if ($objs == null) {
            return true;
        }
        foreach ($objs as $obj) {
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return false;
            }
            array_push($ids, $obj->id);
        }
        if ($ids == []) {
            return true;
        } else {
            return $this->recursionForDelete($ids);
        }
    }

    /**
     * 获取顶级父类Id
     * @param $id
     * @return mixed
     * create by gby 20180927
     */
    public function getParentId($id)
    {
        // 通过id 查找父类id
        $data = XhsysClassification::findFirst($id);
        $iParentId = $data->iParentId;
        $newArray = [];
        if ($iParentId != '0') {
            return $this->getParentId($iParentId);
        } else {
            $newArray['iParentId'] = $id;
            return $id;
        }
    }

    /**
     * 获取学校老师和学生
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20190122
     */
    public function getSchoolMemberAction()
    {
        $schoolIds = $this->request->getPost('schoolIds', 'string');
        if (empty($schoolIds)) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        $data = [];
        foreach ($schoolIds as $key => $schoolId) {
            $parameters = [
                'columns' => 'iUserId,sLogonName,sUserName,iSchoolId,iUserType',
                'conditions' => "bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iSchoolId = {$schoolId} AND iUserType IN (1,4)",
            ];
            $result = XhsysUser::find($parameters)->toArray();
            $children = [];
            foreach ($result as $k => $v) {
                $children[$k]['id'] = $v['iUserId'];
                if ($v['iUserType'] == 1) {
                    $type = '学生';
                } else {
                    $type = '教师';
                }
                $children[$k]['text'] = $v['sUserName'].'('.$type.')'.'-'.$v['sLogonName'];
            }
            $schoolName = XhschoolInfo::getSchoolNameById($schoolId);
            $data[$key]['text'] = $schoolName;
            $data[$key]['children'] = $children;
        }
        return $this->sendJsonResponse($data);
    }


}

